/*
 * @description:
 * @author: <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @Date: 2024-03-10 22:18:14
 * @FilePath: \dynamic-conf\loader\load2Obj.go
 * @LastEditTime: 2024-03-26 23:00:57
 * @LastEditors: <a href="mailto:joshualwork@163.com">joshua_liu</a>
 */
package loader

import (
	"fmt"
	"strings"

	log "github.com/sirupsen/logrus"
)

func GetExtraPropsFromLoader() []*ExtraProps {
	props := []*ExtraProps{}
	mapProps := []map[string]string{}
	if GlobalConfig.IsSet("application.config.nacos.map-files") {
		GlobalConfig.UnmarshalKey("application.config.nacos.map-files", &mapProps)
		log.Info("Loading extra properties from file loader...")
		// jsonStr, error := json.Marshal(&mapProps)
		// if error != nil {
		// 	json.Unmarshal(jsonStr, &props)
		// }
	}
	// globalConfig.UnmarshalKey("application.config.nacos.map-files", &props)
	for _, key := range mapProps {
		tempExtraProps := NewFullConstractExtraProps(key["group"], key["data-id"],
			key["to-file"], key["callback"], key["authorization"])
		props = append(props, tempExtraProps)
		log.Info(fmt.Sprintf("Nacos extra props: '%+v'\n", tempExtraProps))
	}
	for _, key := range props {
		key.Callback = MushualEnvProps(key.Callback)
		key.DataId = MushualEnvProps(key.DataId)
		key.Group = MushualEnvProps(key.Group)
		key.ToPath = MushualEnvProps(key.ToPath)
	}
	return props
}

func MushualEnvProps(value string) string {
	dftRealval := value
	if strings.HasPrefix(value, "${") && strings.HasSuffix(value, "}") {
		realKey := strings.TrimSuffix(strings.TrimPrefix(value, "${"), "}")
		if strings.Contains(realKey, ":") {
			parts := strings.Split(realKey, ":")
			if len(parts) == 2 {
				realKey = parts[0]
				dftRealval = parts[1]
			}
		}
		if GlobalConfig.IsSet(realKey) {
			dftRealval = GlobalConfig.GetString(realKey)
		}
	}
	return dftRealval
}
